﻿using Unity.Burst;
using Unity.Collections;
using Unity.Entities;

[UpdateAfter(typeof(DestroyGameObjectSystem))]
public partial struct DestroyEntitySystem : ISystem
{
    [BurstCompile]
    public void OnCreate(ref SystemState state)
    {
        state.RequireForUpdate<BattleSceneTag>();
    }

    [BurstCompile]
    public void OnUpdate(ref SystemState state)
    {
        using EntityCommandBuffer ecb = new EntityCommandBuffer(Allocator.Temp);

        //敌人数据池
        var enemyPoolEntity = SystemAPI.GetSingletonEntity<PoolEnemyTag>();
        var enemyBuffer = SystemAPI.GetBuffer<PoolElement>(enemyPoolEntity);
        
        //销毁敌人实体
        foreach (var (poolReceiveTag, instantiateGameObjectTag, entity) in
                 SystemAPI.Query<EnabledRefRW<PoolReceiveTag>, EnabledRefRW<InstantiateGameObjectTag>>().WithPresent<InstantiateGameObjectTag>().WithEntityAccess())
        {

            poolReceiveTag.ValueRW = false;
            instantiateGameObjectTag.ValueRW = true;

            ecb.SetEnabled(entity, false);
            enemyBuffer.Add(new PoolElement
            {
                Entity = entity
            });
        }   

        ecb.Playback(state.EntityManager);
    }


}